package com.yl.shiro;

import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.oa.bean.User;
import com.oa.service.impl.PersonalServiceImpl;

public class MyRealm extends AuthorizingRealm {

	@Resource
	PersonalServiceImpl personalServiceImpl;
	
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		String userName = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		Set<String>roles = personalServiceImpl.getRole(userName);
		System.out.println(roles);
		
		
		authorizationInfo.setRoles(roles);	
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		System.out.println("执行登陆验证");
		String userName = (String) token.getPrincipal();
		System.out.println(userName);
		User user = personalServiceImpl.getUserByName(userName);
		System.out.println(user);
		
		if(user!=null){
			if(!"正常".equals(user.getUstate())){
				return null;
			}
			AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getUsername(),user.getUpass(),"myRealm");
			HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
			HttpSession session = request.getSession();
			session.setAttribute("uid", user.getUid());
			session.setAttribute("deptno", user.getUdepartment_id());
			session.setAttribute("uname", user.getUname());
			session.setAttribute("username", user.getUsername());
			session.setAttribute("role", user.getUrole());
			return authcInfo;
		}
		return null;
	}

}
